<?php

require_once('config.php');
require_once('./adodb/adodb.inc.php');

$conn = &ADONewConnection('mysql');                                                             
$conn->connect($DBServer, $DBUsername, $DBPassword, $DBDatabase);
$conn->EXECUTE("set names 'utf8'");

$filename   = $_FILES["file"]["tmp_name"];
$handle = fopen($filename,'rb');
fseek($handle, 3);
$auth   = array();
$tmpname= '';

while (!feof($handle)) {
    $buffer = fgets($handle);
    if(trim($buffer) && strpos($buffer,'[')===0){
        $tmpname = trim($buffer);
        $auth[$tmpname] = array();
        continue;
    } else if(trim($buffer)){
        $tmpbuffer = explode('=', $buffer);
        if(count($tmpbuffer) > 1)
            $auth[$tmpname][trim($tmpbuffer[0])] = trim($tmpbuffer[1]);
        else $auth[$tmpname][trim($tmpbuffer[0])] = '';
    }
}

foreach ($auth as $key => $value) {
    $repoPath   = explode(':', trim($key, ' []'));
    if (count($repoPath)>1) {
        $repo   = $repoPath[0];
        $path   = pathFilter($repoPath[1]);
        $repoid = repoAdd($conn, $repo);

        foreach ($value as $name => $auth) {
            $tmpauth    = '';
            switch(trim($auth)){
                case 'rw':
                    $tmpauth    = 3;
                    break;
                case 'w':
                    $tmpauth    = 2;
                    break;
                case 'r':
                    $tmpauth    = 1;
                    break;
                default:
                    $tmpauth    = 0;
            }
            if (strpos(trim($name), '@')===0 && $tmpauth != 0 ) {
                $tmpname    = trim($name, '@ ');
                addPrivileges($conn, $tmpname, $repoid, $path, $tmpauth, 'group' );
            } else if(trim($name) && $tmpauth != 0 ){
                $tmpname    = trim($name);
                addPrivileges($conn, $tmpname, $repoid, $path, $tmpauth, 'user');
            }
        }
    } else {
        insertUserGroups($conn, $auth[$key]);
    }
}
//print_r($auth);
fclose($handle);

function insertUserGroups($db, $groups) {
    foreach($groups as $groupname => $users) {
        $s_groupname= makeSqlString(trim($groupname, ' []'));
        $results    = $db->Execute("SELECT * FROM groups WHERE name = $s_groupname");
        $s_groupid  = '';
        $s_userid   = '';

        if(!$results->fields){
            $db->Execute("INSERT INTO groups (id, name) VALUES (null, $s_groupname)");
            $results2   = $db->Execute("SELECT * FROM groups WHERE name = $s_groupname");
            $s_groupid  = $results2->fields['id'];
        } else {
            $s_groupid  = $results->fields['id'];
        }

        $s_users    = array(); 
        if(trim($users)){
            $s_users= explode(',', $users);
            foreach($s_users as $user) {
                if (trim($user)) {
                    $s_username = makeSqlString(trim($user));
                    $results    = $db->Execute("SELECT * FROM users WHERE name = $s_username");
                    if(!$results->fields){
                        $db->Execute("INSERT INTO users (id, name) VALUES (null, $s_username)");
                        $results    = $db->Execute("SELECT * FROM users WHERE name = $s_username");
                    }
                    $s_userid   = $results->fields['id'];
                    $results3   = $db->Execute("SELECT * FROM usersgroups WHERE userid = $s_userid AND groupid = $s_groupid");
                    if(!$results3->fields)
                        $db->Execute("INSERT INTO usersgroups (userid, groupid) VALUES ($s_userid, $s_groupid)");
                }
            }
        }
    }
}

function repoAdd($db, $name) {
    $s_name     = makeSqlString($name);
    require('config.php');

    $a_dir      = $svn_repos_loc.DIRECTORY_SEPARATOR.escapeshellarg($name);

    $results    = $db->Execute("SELECT * FROM repositories WHERE name = $s_name");
    if(!$results->fields) {
        $db->Execute("INSERT INTO repositories (id, name, ownerid) VALUES (null, $s_name, 544)");
        $ret = exec("$svnadmin_cmd --config-dir $svn_config_dir create $a_dir");                         
        if($ret!="") {
            print("svnadmin failed: $ret");
        }
        $results    = $db->Execute("SELECT * FROM repositories WHERE name = $s_name");
    }
    return $results->fields['id'];
}

function addPrivileges($db, $name, $repositoryId, $path, $access, $option) {

    $o_table    = $option . 's';
    $o_pritable = $option . 'privileges';
    $o_id       = $option . 'id';

    $s_name     = makeSqlString($name);
    $results    = $db->Execute("SELECT id FROM $o_table WHERE name = $s_name");
    if (!$results->fields) {
        $db->Execute("INSERT INTO $o_table (id, name) VALUES (null, $s_name)");
        $results= $db->Execute("SELECT id FROM $o_table WHERE name = $s_name");
    }
    $s_id       = $results->fields['id'];

    $s_repositoryId     = makeSqlString($repositoryId);
    $s_path     = makeSqlString($path);
    $s_access   = makeSqlString($access);

    $results = $db->Execute("SELECT * FROM $o_pritable WHERE $o_id = $s_id AND repositoryid = $s_repositoryId AND path = $s_path");
    if(!$results)
        print $db->ErrorMsg;
    else
        if ($results->fields) {
            $db->Execute("UPDATE $o_pritable SET access = $s_access WHERE $o_id = $s_id AND repositoryid = $s_repositoryId AND path = $s_path");
        } else {
            $db->Execute("INSERT INTO $o_pritable (id, $o_id, repositoryid, path, access) VALUES (null, $s_id, $s_repositoryId, $s_path, $s_access)");
        }
}

function makeSqlString($sql) {
    return "'" . str_replace("'", "''", $sql) . "'";
}

function pathFilter($path) {
    return ($path == '/')?$path:rtrim($path, '/');
}
